package com.jinyang.jetpackdemo.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.jinyang.jetpackdemo.R
import org.greenrobot.eventbus.EventBus
import com.jinyang.jetpackdemo.util.LjyLogUtil
import org.greenrobot.eventbus.Subscribe

import org.greenrobot.eventbus.ThreadMode
import com.jinyang.jetpackdemo.MyEventBusIndex
import com.jinyang.jetpackdemo.util.gson.GsonUtils
import com.jinyang.jetpackdemo.util.event.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class EventBusActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_event_bus)


        val type = 3
        when (type) {
            3 -> {
                lifecycleScope.launch(Dispatchers.Main) {
                    observeEvent {
                        LjyLogUtil.d("FlowBus.register1:${GsonUtils.toJson(it)}_${Thread.currentThread().name}")
                    }
                    observeEvent(Dispatchers.IO) {
                        LjyLogUtil.d("FlowBus.register2:${GsonUtils.toJson(it)}_${Thread.currentThread().name}")
                    }

                    observeEvent(Dispatchers.Main) {
                        LjyLogUtil.d("FlowBus.register3:${GsonUtils.toJson(it)}_${Thread.currentThread().name}")
                    }
                }

                lifecycleScope.launch(Dispatchers.IO) {
                    delay(1000)
                    postValue(EventMessage(100))
                    postValue(EventMessage(101), 1000)
                    postValue(EventMessage(102, "bbb"), dispatcher = Dispatchers.IO)
                    val event3 = EventMessage(103, "ccc")
                    event3.put("key1", 123)
                    event3.put("key2", "abc")
                    postValue(event3, 2000, dispatcher = Dispatchers.Main)

                    // 发送消息
                    SharedFlowBus.with(EventMessage::class.java).tryEmit(EventMessage(100))
                    // 发送粘性消息
                    SharedFlowBus.withSticky(EventMessage::class.java)
                        .tryEmit(EventMessage(200))

                    // 订阅消息
                    SharedFlowBus.on(EventMessage::class.java)
                        .observe(this@EventBusActivity) {
                            println(it)
                        }
                    // 订阅粘性消息
                    SharedFlowBus.onSticky(EventMessage::class.java)
                        .observe(this@EventBusActivity) {
                            println(it)
                        }
                }
            }
            2 -> {
                FlowBus.instance.with(EventMessage::class.java).observeEvent(this) {
                    LjyLogUtil.d("FlowBus.register1:${GsonUtils.toJson(it)}_${Thread.currentThread().name}")
                }
                lifecycleScope.launch(Dispatchers.IO) {
                    withContext(Dispatchers.Main) {//不创建新的协程，指定协程上运行代码块,可以切换线程
                        FlowBus.instance.with(EventMessage::class.java)
                            .observeEvent(this@EventBusActivity) {
                                LjyLogUtil.d("FlowBus.register2:${GsonUtils.toJson(it)}_${Thread.currentThread().name}")
                            }
                    }
                }
                FlowBus.instance.with(EventMessage::class.java).observeEvent(this) {
                    LjyLogUtil.d("FlowBus.register3:${GsonUtils.toJson(it)}_${Thread.currentThread().name}")
                }
                lifecycleScope.launch(Dispatchers.Main) {

                    val event = EventMessage(111)
                    LjyLogUtil.d(
                        "FlowBus:send1_${Thread.currentThread().name}_${
                            GsonUtils.toJson(
                                event
                            )
                        }"
                    )
                    FlowBus.instance.with(EventMessage::class.java).setValue(event)
                    delay(2000)
                    FlowBus.instance.with(EventMessage::class.java)
                        .setValue(EventMessage(101))
                    FlowBus.instance.with(EventMessage::class.java)
                        .setValue(EventMessage(102))
                    FlowBus.instance.with(EventMessage::class.java)
                        .setValue(EventMessage(103))
                    FlowBus.instance.with(EventMessage::class.java)
                        .setValue(EventMessage(104))
                    FlowBus.instance.with(EventMessage::class.java)
                        .setValue(EventMessage(105))
                }
                lifecycleScope.launch(Dispatchers.IO) {
                    delay(4000)
                    val event = EventMessage(222, "bbb")
                    LjyLogUtil.d(
                        "FlowBus:send2_${Thread.currentThread().name}_${
                            GsonUtils.toJson(
                                event
                            )
                        }"
                    )
                    FlowBus.instance.with(EventMessage::class.java).setValue(event)
                }
                lifecycleScope.launch(Dispatchers.Default) {
                    delay(6000)
                    withContext(Dispatchers.Main) {
                        val event = EventMessage(333, "ccc")
                        event.put("key1", 123)
                        event.put("key2", "abc")
                        LjyLogUtil.d(
                            "FlowBus:send3_${Thread.currentThread().name}_${
                                GsonUtils.toJson(
                                    event
                                )
                            }"
                        )
                        FlowBus.instance.with(EventMessage::class.java).setValue(event)
                    }
                }
            }
            1 -> {
                LiveDataBus.instance
                    .with(EventMessage::class.java)
                    .observe(this, {
                        LjyLogUtil.d("LiveDataBus:${GsonUtils.toJson(it)}")
                    })
                LiveDataBus.instance
                    .with(EventMessage::class.java)
                    .observe(this, {
                        LjyLogUtil.d("LiveDataBus2:${GsonUtils.toJson(it)}")
                    })
                LjyLogUtil.d("LiveDataBus:send")

                LiveDataBus.instance
                    .with(EventMessage::class.java).postValue(
                        EventMessage(123, "acb")
                    )
                val event2 = EventMessage(456, "def")
                event2.put("key1", 111)
                event2.put("key2", "value2")
                LiveDataBus.instance
                    .with(EventMessage::class.java).postValue(event2)
                LiveDataBus.instance
                    .with(EventMessage::class.java).postValue(
                        EventMessage(789, "qwer")
                    )
            }
            0 -> {
//            LiveEventBus.get(EventBusMessage::class.java)
//                .observe(this, {
//                    LjyLogUtil.d("LiveEventBus:${it.key}")
//                    LjyLogUtil.d("LiveEventBus:${it.message}")
//                })
//            LiveEventBus.get(EventBusMessage::class.java)
//                .observe(this, {
//                    LjyLogUtil.d("LiveEventBus2:${it.key}")
//                    LjyLogUtil.d("LiveEventBus2:${it.message}")
//                })
//            LjyLogUtil.d("LiveEventBus:send")
//            LiveEventBus.get(EventBusMessage::class.java).post(
//                EventBusMessage(123, "acb")
//            )
//            LiveEventBus.get(EventBusMessage::class.java).post(
//                EventBusMessage(456, "def")
//            )
//            LiveEventBus.get(EventBusMessage::class.java).post(
//                EventBusMessage(789, "qwer")
//            )
            }
            -1 -> {
                //        val mEventBus = EventBus.builder().addIndex(MyEventBusIndex()).build()
                EventBus.builder().addIndex(MyEventBusIndex()).installDefaultEventBus()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        //1. 注册
        EventBus.getDefault().register(this)
    }

    //2. 自定义Event
    class MessageEvent(val what: Int)

    //3. 订阅
//    @Subscribe(threadMode = ThreadMode.POSTING)
    @Subscribe(threadMode = ThreadMode.MAIN)
//    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
//    @Subscribe(threadMode = ThreadMode.BACKGROUND)
//    @Subscribe(threadMode = ThreadMode.ASYNC)
    fun onMessageEvent(event: MessageEvent?) {
        LjyLogUtil.d("onMessageEvent: ${Thread.currentThread().name}_event.what=${event?.what}")
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onMessageEventSticky(event: MessageEvent?) {
        LjyLogUtil.d("onMessageEventSticky：${Thread.currentThread().name}_event.what=${event?.what}")
    }


    fun onBtnCLick(view: android.view.View) {
        when (view.id) {
            R.id.btn_postInMain -> {
                //4. 在主线程发布
                LjyLogUtil.d("${Thread.currentThread().name}_post")
                EventBus.getDefault().post(MessageEvent(1001))
            }
            R.id.btn_postInThread -> {
                //4. 在子线程发布
                Thread {
                    LjyLogUtil.d("${Thread.currentThread().name}_post")
                    EventBus.getDefault().post(MessageEvent(1002))
                }.start()
            }
            R.id.btn_register -> {
                EventBus.getDefault().register(this)
            }
            R.id.btn_postSticky -> {
                LjyLogUtil.d("${Thread.currentThread().name}_postSticky")
                EventBus.getDefault().postSticky(MessageEvent(1003))
            }
        }
    }

    override fun onStop() {
        super.onStop()
        //5. 注销
        EventBus.getDefault().unregister(this)
    }
}
